import Bb from 'backbone';
import {
    formatAmount
} from 'math.js';
import Radio from 'backbone.radio';
import BaseModel from 'base/models/BaseModel';

const TotalModel = BaseModel.extend({
    isLocalModel: true, // Avoids to be saved to server
    /**
     * @param {*} tva_key : The TVA's value 
     * @returns The TVA's name (label)
     */
    getTvaOptionLabel: function (tva_key) {
        const channel = Radio.channel('config');
        const tva_options = channel.request('get:options', 'tvas');
        const tva_option = tva_options.find(option => option.value == tva_key);
        return tva_option ? tva_option.name : "Inconnue";
    },
    tva_labels: function () {
        var values = [];
        for (const [key, value] of Object.entries(this.get('tvas'))) {
            const label = this.getTvaOptionLabel(key);
            values.push({
                'label': label,
                value: formatAmount(value, true)
            })
        }
        return values;
    },
    /**
     * 
     * @returns values of the tva objects used in the document
     */
    tva_values: function () {
        if (this.has('tvas')) {
            // Return tva values used in the form in float format
            const result = Object.keys(this.get('tvas')).map(tva => parseFloat(tva));
            return result;
        } else {
            return {};
        }
    },
    hasContributions() {
        let contribution = 0;
        let insurance = 0;
        if (this.hasPriceStudy()) {
            const contributions = this.get('price_study').contributions;
            contribution = contributions['cae'] || 0;
            insurance = contributions['insurance'] || 0;
        }
        return contribution != 0 || insurance != 0;
    },
    hasPriceStudy() {
        return this.has('price_study');
    }
});
export default TotalModel;